home *** CD-ROM | disk | FTP | other *** search
- /*
- * head - a program to print out the first n lines of a file.
- * Author: Edwin Hoogerbeets
- */
-
- #include <stdio.h>
- #include <ctype.h>
-
- #define toint(a) (int)((a) - '0')
-
- main(argc,argv)
- int argc;
- char **argv;
- {
- register int lines = 10, multiple_files, index = 1;
-
- /* if there are no arguments, take from the stdin */
- if ( argc == 1 ) {
- head(stdin,lines);
- exit(0);
- }
-
- /* if the first argument starts with '-', assume it is an option */
- if ( *argv[index] == '-' ) {
- register char *foo;
-
- lines = 0;
-
- /* pointer to character after the dash */
- foo = &argv[index][1];
-
- /* get the number of lines to display */
- while ( isdigit(*foo) ) {
- lines = lines*10 + toint(*foo++);
- }
-
- /* increment so that we don't try to print out the file '-99' below! */
- ++index;
- }
-
- /* see how many arguments are left */
- switch ( argc - index ) {
-
- /* none, so there must only have been a -nn argument */
- case 0:
- head(stdin,lines);
- exit(0);
-
- /* only one, so make a note of that */
- case 1:
- multiple_files = 0;
- break;
-
- /* more than one. (argc - index) cannot be negative */
- default:
- multiple_files = 1;
- break;
- }
-
- /* for each of the remaining args, open them and "head" them */
- for ( ; index < argc ; index++ ) {
- register FILE *in;
-
- /* only print this header line if there is more than one file */
- if ( multiple_files ) {
- printf("==> %s <==\n",argv[index]);
- }
-
- if ( (in = fopen(argv[index],"r")) == NULL ) {
- fprintf(stderr,"Warning: could not open file %s\n",argv[index]);
- } else {
- head(in,lines);
- fclose(in);
- }
- }
- }
-
- /*
- * read "num" lines from the file "file" and print them to the stdout
- */
- head(file,num)
- FILE *file;
- int num;
- {
- char buffer[BUFSIZ]; /* line lengths limited to BUFSIZ :-( */
- register int count;
-
- for ( count = 0; count < num; count++ ) {
- if ( !feof(file) ) {
- fgets(buffer,BUFSIZ,file);
- fputs(buffer,stdout);
- }
- }
- }
-
-